package com.song.config;

import com.song.properties.MasterProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.jndi.JndiObjectFactoryBean;

import javax.sql.DataSource;

@Configuration
public class DataSourceConfing {

    @Autowired
    private MasterProperties masterProperties;

    /**
     * jndi配置数据源
     */
   /* @Profile("production")
    @Bean(name = "jdniDataSource")
    public JndiObjectFactoryBean jdniDataSource() {
        JndiObjectFactoryBean jndiObjectFB = new JndiObjectFactoryBean();
        jndiObjectFB.setJndiName("jdbc/SongDS");
        jndiObjectFB.setResourceRef(true);
        jndiObjectFB.setProxyInterface(javax.sql.DataSource.class);
        return jndiObjectFB;
    }*/


    /**
     * 基于jdbc配置数据源
     */
    @Profile("development")
    @Bean(name="jdbcDataSource")
    public DataSource jdbcDataSource() {
        //  在每次连接请求时都会返回一个新建的连接,该连接没有提供池化管理
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName(masterProperties.getDriverClassName());
        ds.setUrl(masterProperties.getUrl());
        ds.setUsername(masterProperties.getUsername());
        ds.setPassword(masterProperties.getPassword());
        return ds;
    }


    /**
     * 使用嵌入式数据库，配置数据源
     */
    @Profile("production")
    @Bean(name = "embeddedDataSource")
    public DataSource embeddedDataSource(){
        return new EmbeddedDatabaseBuilder()
                .setType(EmbeddedDatabaseType.H2)
                .addScript("classpath:schema.sql")
                .build();
    }

    @Bean
    public JdbcTemplate jdbcTemplate( @Qualifier("jdbcDataSource") DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }

}
